﻿using MahApps.Metro.Controls;
using Minecraft_Armor_Stand_Creater.Util;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows;

namespace Minecraft_Armor_Stand_Creater.Resource.Windows
{
    /// <summary>
    /// VersionMessager.xaml 的交互逻辑
    /// </summary>
    public partial class VersionMessager : MetroWindow
    {
        bool updated;

        public VersionMessager()
        {
            InitializeComponent();

            Loaded += Window_Loaded;
            Closed += Window_Closed;
            ExeButton.Click += Update_Click;
        }

        void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        void Window_Closed(object sender, EventArgs e)
        {
            if (updated)
            {
                Process.Start(@".\MAS Updater.exe");
                Log.WriteToFile("[Main]开始升级程序");
                Environment.Exit(0);
            }
        }

        void Update_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ExeButton.Content = FindResource("UpdaterDownloading");
                ExeButton.IsEnabled = false;
                Thread th_updaterDownload = new(new ThreadStart(delegate
                {
                    //向目标网页发送Post请求
                    Stream responseStream = WebRequest.Create(VersionData.Instance.updaterlink).GetResponse().GetResponseStream();
                    //创建本地文件写入流
                    using (Stream stream = new FileStream(@".\MAS Updater.exe", FileMode.Create))
                    {
                        byte[] bArr = new byte[1024];
                        int size = responseStream.Read(bArr, 0, bArr.Length);
                        while (size > 0)
                        {
                            stream.Write(bArr, 0, size);
                            size = responseStream.Read(bArr, 0, bArr.Length);
                        }
                    }
                    responseStream.Close();

                    updated = true;
                    Dispatcher.Invoke(new ThreadStart(delegate
                    {
                        Close();
                    }));
                }));

                th_updaterDownload.Start();
            }
            catch
            {
                ExeButton.Content = FindResource("Retry");
                Log.WriteToFile("[VersionMessager]更新器下载失败");
                MessageBox.Show(FindResource("UpdaterDownloadFail") as string, "Error");
            }
            finally
            {
                ExeButton.IsEnabled = true;
            }
        }
    }
}
